<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '绘本集详情',
  },
}
</route>

<script lang="ts" setup>
import type { BookSetDetailRespVO, FavoriteOperationReqVO, PictureBookRespVO } from '@/api'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { computed, onMounted, ref } from 'vue'
import { addBookFavorite, checkBookFavoriteStatus, getBookSetDetail, removeBookFavorite } from '@/api/book'
import { clearFavoritesCache } from '@/api/favorites'
import { addToRecycleBin } from '@/api/recycle-bin'

// 获取状态栏高度
const statusBarHeight = ref(0)

// 页面参数
const bookSetId = ref('')
const bookSetTitle = ref('')
const bookSetCover = ref('')
const bookSetDescription = ref('')

// 排序和功能状态
const sortType = ref('default') // 'default' | 'title'
const isFavorited = ref(false)

// 计算属性：判断标题是否过长
const isLongTitle = computed(() => {
  return bookSetTitle.value && bookSetTitle.value.length > 8
})

// 加载状态
const loading = ref(false)
const favoriteLoading = ref(false)

// 绘本集详情数据
const bookSetDetail = ref<BookSetDetailRespVO | null>(null)

// 绘本图片集列表数据
const pictureBooks = ref<PictureBookRespVO[]>([])

// 排序后的绘本列表
const sortedPictureBooks = computed(() => {
  const books = [...pictureBooks.value]

  if (sortType.value === 'title') {
    // 按书名A-Z排序
    return books.sort((a, b) => a.title.localeCompare(b.title))
  }

  // 默认排序（保持原有顺序）
  return books
})

// 设置排序类型
function setSortType(type: string) {
  sortType.value = type
  console.log('排序类型切换为:', type)
}

// API调用函数
async function loadBookSetDetail(id: string) {
  try {
    loading.value = true
    const response = await getBookSetDetail(Number(id))

    // 检查响应是否有效 - 修复响应结构处理
    if (response && response.code === 0) {
      const detailData = response.data
      bookSetDetail.value = detailData
      bookSetTitle.value = detailData.title
      bookSetCover.value = detailData.cover
      bookSetDescription.value = detailData.description || ''
      pictureBooks.value = detailData.books || []
      console.log('绘本集详情加载成功:', detailData.title)
    }
    else {
      console.warn('绘本集详情API响应格式异常:', response)
      throw new Error(response?.msg || 'API响应异常')
    }
  }
  catch (error) {
    console.error('加载绘本集详情失败:', error)
    // 使用备用数据
    setBookSetInfo(id)
  }
  finally {
    loading.value = false
  }
}

async function loadFavoriteStatus(id: string) {
  try {
    const response = await checkBookFavoriteStatus(Number(id), 'book_set')

    // 检查响应是否有效 - 后端直接返回 Boolean 值
    if (response && response.code === 0) {
      isFavorited.value = response.data // 修复：后端返回的 data 直接是 Boolean 值
      console.log('收藏状态加载成功:', response.data)
    }
    else {
      console.warn('收藏状态API响应格式异常:', response)
      // 默认为未收藏状态
      isFavorited.value = false
    }
  }
  catch (error) {
    console.error('检查收藏状态失败:', error)
    // 默认为未收藏状态
    isFavorited.value = false
  }
}

// 切换收藏状态
async function toggleFavorite() {
  try {
    favoriteLoading.value = true
    const favoriteData: FavoriteOperationReqVO = {
      targetId: Number(bookSetId.value),
      targetType: 'book_set',
    }

    if (isFavorited.value) {
      // 取消收藏
      const response = await removeBookFavorite(favoriteData)
      if (response && response.code === 0) {
        isFavorited.value = false
        // 清除收藏相关缓存
        clearFavoritesCache()
        uni.showToast({
          title: '已取消收藏',
          icon: 'success',
          duration: 1500,
        })
      }
      else {
        throw new Error(response?.msg || '取消收藏失败')
      }
    }
    else {
      // 添加收藏
      const response = await addBookFavorite(favoriteData)
      if (response && response.code === 0) {
        isFavorited.value = true
        // 清除收藏相关缓存
        clearFavoritesCache()
        uni.showToast({
          title: '已收藏',
          icon: 'success',
          duration: 1500,
        })
      }
      else {
        throw new Error(response?.msg || '收藏失败')
      }
    }
  }
  catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'error',
      duration: 1500,
    })
  }
  finally {
    favoriteLoading.value = false
  }
}

onLoad((options: any) => {
  // 获取页面参数
  bookSetId.value = options.setId || options.id || ''
  bookSetTitle.value = decodeURIComponent(options.title || '绘本集')

  // 加载绘本集详情
  if (bookSetId.value) {
    loadBookSetDetail(bookSetId.value)
    loadFavoriteStatus(bookSetId.value)
  }
})

onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
})

onShow(() => {
  // 页面显示时重新加载数据，确保阅读状态是最新的
  if (bookSetId.value) {
    console.log('页面显示，重新加载绘本集数据以更新阅读状态')
    // 添加小延迟确保阅读记录已保存完成
    setTimeout(() => {
      loadBookSetDetail(bookSetId.value)
    }, 200)
  }
})

// 根据绘本集ID设置信息
function setBookSetInfo(id: string) {
  const bookSetData: Record<string, any> = {
    1: {
      title: '一年级古诗词',
      cover: 'https://img1.doubanio.com/view/subject/s/public/s1130906.jpg',
      description: '精选一年级必背古诗词，配有精美插图和拼音标注，帮助孩子轻松学习古典诗词。',
    },
    2: {
      title: '成语故事精选',
      cover: 'https://img2.doubanio.com/view/subject/s/public/s2768378.jpg',
      description: '经典成语故事合集，通过生动有趣的故事让孩子理解成语含义，提升语文素养。',
    },
    3: {
      title: 'RAZ AA级',
      cover: 'https://picsum.photos/300/400?random=3',
      description: 'Reading A-Z是美国著名的分级阅读体系，RAZ AA级适合英语启蒙阶段的孩子，内容简单有趣。',
    },
    4: {
      title: '红火箭预备级',
      cover: 'https://picsum.photos/300/400?random=4',
      description: '红火箭分级阅读是澳大利亚专业分级阅读出版社Flying Start Books出版的系列读物，适合启蒙阶段。',
    },
    5: {
      title: '廖彩杏第一阶段',
      cover: 'https://picsum.photos/300/400?random=5',
      description: '廖彩杏书单是台湾著名英语启蒙专家廖彩杏推荐的英文绘本书单，第一阶段适合英语启蒙。',
    },
    6: {
      title: '神奇校车系列',
      cover: 'https://picsum.photos/300/400?random=6',
      description: '让孩子在阅读中探索科学奥秘，跟随弗瑞丝老师和神奇校车一起进行奇妙的科学冒险之旅。',
    },
    // 中文书架绘本集数据
    11: {
      title: '一年级古诗词',
      cover: 'https://img1.doubanio.com/view/subject/s/public/s1130906.jpg',
      description: '精选一年级必背古诗词，配有精美插图和拼音标注，帮助孩子轻松学习古典诗词。',
    },
    12: {
      title: '二年级古诗词',
      cover: 'https://img2.doubanio.com/view/subject/s/public/s2768378.jpg',
      description: '二年级必背古诗词精选，内容丰富，配有详细注释和朗读音频。',
    },
    13: {
      title: '三年级古诗词',
      cover: 'https://img1.doubanio.com/view/subject/s/public/s6384944.jpg',
      description: '三年级古诗词学习必备，包含经典名篇，培养孩子的文学素养。',
    },
    14: {
      title: '四年级古诗词',
      cover: 'https://img2.doubanio.com/view/subject/s/public/s1070959.jpg',
      description: '四年级古诗词精选集，涵盖唐诗宋词经典作品，提升文学鉴赏能力。',
    },
    15: {
      title: '五年级古诗词',
      cover: 'https://img1.doubanio.com/view/subject/s/public/s1144911.jpg',
      description: '五年级古诗词学习资料，包含历代名家作品，深化古典文学理解。',
    },
    16: {
      title: '六年级古诗词',
      cover: 'https://img2.doubanio.com/view/subject/s/public/s1207932.jpg',
      description: '六年级古诗词总复习，汇集小学阶段重要诗词作品，为升学做准备。',
    },
  }

  const defaultData = {
    title: bookSetTitle.value || '精选绘本集',
    cover: 'https://picsum.photos/300/400?random=default',
    description: '精心挑选的优质绘本集合，为孩子提供丰富的阅读体验和成长启发。',
  }

  const data = bookSetData[id] || defaultData
  bookSetTitle.value = data.title
  bookSetCover.value = data.cover
  bookSetDescription.value = data.description

  // 初始化绘本数据
  pictureBooks.value = []
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 显示完整标题
function showFullTitle() {
  if (bookSetTitle.value && bookSetTitle.value.length > 8) {
    // 使用模态框显示完整标题，提供更好的阅读体验
    uni.showModal({
      title: '绘本集名称',
      content: bookSetTitle.value,
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#007AFF',
    })
  }
}

// 显示删除确认弹窗
function showDeleteConfirm() {
  uni.showModal({
    title: '确认删除',
    content: `确定要将"${bookSetTitle.value}"移入回收站吗？删除后可在回收站中恢复。`,
    showCancel: true,
    cancelText: '取消',
    confirmText: '删除',
    confirmColor: '#ff4757',
    success: (res) => {
      if (res.confirm) {
        deleteBookSet()
      }
    },
  })
}

// 删除绘本集
async function deleteBookSet() {
  try {
    // 显示加载提示
    uni.showLoading({
      title: '删除中...',
      mask: true,
    })

    // 调用API将绘本集添加到回收站
    await addToRecycleBin({
      itemType: 'book_set',
      itemId: Number(bookSetId.value),
      deletedFrom: 'book_set_detail',
      groupTitle: bookSetTitle.value,
    })

    // 隐藏加载提示
    uni.hideLoading()

    // 显示成功提示
    uni.showToast({
      title: '已移入回收站',
      icon: 'success',
      duration: 2000,
    })

    // 延迟返回上一页，让用户看到成功提示
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
  catch (error) {
    // 隐藏加载提示
    uni.hideLoading()

    console.error('删除绘本集失败:', error)

    // 显示错误提示
    uni.showToast({
      title: '删除失败，请重试',
      icon: 'error',
      duration: 2000,
    })
  }
}

// 打开绘本图片集
function openPictureBook(book: any) {
  // 跳转到绘本阅读页面
  uni.navigateTo({
    url: `/pages-sub/reading/picture-book-reader/index?bookId=${book.id}&title=${encodeURIComponent(book.title)}&pages=${book.pages}`,
  })
}
</script>

<template>
  <view class="picture-book-set-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: `${statusBarHeight}px` }">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <uni-icons type="left" size="20" color="#333" />
          <text class="back-text">
            返回
          </text>
        </view>
        <view class="navbar-title" @click="showFullTitle">
          <text class="title-text" :title="bookSetTitle">
            {{ bookSetTitle }}
          </text>
          <!-- <text v-if="isLongTitle" class="ellipsis-hint">...</text> -->
        </view>
        <view class="navbar-right" />
      </view>
    </view>

    <!-- 绘本集信息 -->
    <view class="book-set-info">
      <view class="set-header">
        <image class="set-cover" :src="bookSetCover" mode="aspectFill" />
        <view class="set-details">
          <text class="set-title">
            {{ bookSetTitle }}
          </text>
          <text class="set-description">
            {{ bookSetDescription }}
          </text>
          <text class="set-count">
            共 {{ pictureBooks.length }} 本绘本
          </text>
        </view>
        <!-- 删除按钮 -->
        <view class="delete-btn-container" @click="showDeleteConfirm">
          <view class="delete-btn">
            <uni-icons
              type="trash"
              size="18"
              color="#607d8b"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 排序和功能按钮组 -->
    <view class="function-bar">
      <view class="sort-buttons">
        <view
          class="sort-btn"
          :class="{ active: sortType === 'default' }"
          @click="setSortType('default')"
        >
          <text class="sort-text">
            默认排序
          </text>
        </view>
        <view
          class="sort-btn"
          :class="{ active: sortType === 'title' }"
          @click="setSortType('title')"
        >
          <text class="sort-text">
            书名排序
          </text>
        </view>
      </view>
      <view class="action-buttons">
        <view
          class="action-btn"
          :class="{ active: isFavorited }"
          @click="toggleFavorite"
        >
          <uni-icons
            :type="isFavorited ? 'heart-filled' : 'heart'"
            size="16"
            :color="isFavorited ? '#ff4757' : '#666'"
          />
          <text class="action-text" :class="{ favorited: isFavorited }">
            收藏
          </text>
        </view>
      </view>
    </view>

    <!-- 绘本图片集列表 -->
    <view class="picture-books-section">
      <view class="section-title">
        绘本图片集列表
      </view>
      <view class="books-grid">
        <view
          v-for="book in sortedPictureBooks"
          :key="book.id"
          class="book-grid-item"
          @click="openPictureBook(book)"
        >
          <view class="book-cover-container">
            <image class="book-cover-grid" :src="book.cover" mode="aspectFill" />
            <!-- 阅读状态标识 -->
            <view v-if="book.readStatus?.isRead || book.isCompleted || (book as any).isRead" class="read-badge">
              已读
            </view>
            <view v-else class="unread-badge">
              未读
            </view>
            <!-- 绘本页数 -->
            <view class="book-pages">
              {{ book.pages }}页
            </view>
          </view>
          <text class="book-title-grid">
            {{ book.title }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.picture-book-set-container {
  min-height: 100vh;
  background: $bg-gradient;
}

/* 自定义导航栏 - 儿童友好风格 */
.custom-navbar {
  @include glass-effect(0.95);
  border-bottom: 1px solid $border-color-light;
  backdrop-filter: $glass-blur;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 $spacing-xl;

    .navbar-left {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding: $spacing-sm;
      border-radius: $border-radius-md;
      transition: $transition-all;

      &:active {
        background-color: $light-gray;
        transform: scale(0.95);
      }

      .btn-icon {
        font-size: $font-size-lg;
      }

      .back-text {
        margin-left: $spacing-sm;
        font-size: $font-size-md;
        color: $dark-gray;
        font-family: $font-family;
        font-weight: $font-weight-medium;
      }
    }

    .navbar-title {
      flex: 1;
      text-align: center;
      max-width: 180px;
      cursor: pointer; // 添加指针样式，表明可点击

      &:active {
        opacity: 0.7; // 点击时的视觉反馈
      }

      .title-text {
        font-size: $font-size-lg;
        font-weight: $font-weight-semibold;
        color: $dark-gray;
        font-family: $font-family;
        // 文本溢出处理
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: calc(100% - 20px); // 为省略号提示留出空间
        display: inline-block;
        // 添加过渡效果
        transition: all 0.2s ease;
      }
    }

    .navbar-right {
      width: 60px; // 占位，保持标题居中
    }
  }
}

/* 绘本集信息 - 儿童友好风格 */
.book-set-info {
  @include glass-effect;
  padding: $spacing-2xl $spacing-xl;
  margin: $spacing-md;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;

  .set-header {
    display: flex;
    position: relative;

    .set-cover {
      width: 80px;
      height: 110px;
      border-radius: $border-radius-md;
      margin-right: $spacing-xl;
      box-shadow: $shadow-md;
    }

    .set-details {
      flex: 1;

      .set-title {
        display: block;
        font-size: $font-size-xl;
        font-weight: $font-weight-semibold;
        color: $dark-gray;
        font-family: $font-family;
        margin-bottom: $spacing-sm;
        width: 80%;
      }

      .set-description {
        display: block;
        font-size: $font-size-base;
        color: $medium-gray;
        line-height: $line-height-relaxed;
        font-family: $font-family;
        margin-bottom: $spacing-md;
      }

      .set-count {
        display: block;
        font-size: $font-size-sm;
        color: $medium-gray;
        font-family: $font-family;
      }
    }

    .delete-btn-container {
      position: absolute;
      top: -10px;
      right: 0;
      cursor: pointer;

      .delete-btn {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: rgba(96, 125, 139, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(96, 125, 139, 0.2);

        &:hover {
          background-color: rgba(96, 125, 139, 0.2);
          transform: scale(1.05);
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }
}

/* 排序和功能按钮组 - 儿童友好风格 */
.function-bar {
  @include glass-effect;
  padding: $spacing-xl;
  margin: 0 $spacing-md $spacing-md;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .sort-buttons {
    display: flex;
    gap: $spacing-xl;

    .sort-btn {
      padding: $spacing-sm $spacing-lg;
      border-radius: $border-radius-3xl;
      background-color: $light-gray;
      cursor: pointer;
      transition: $transition-all;

      .sort-text {
        font-size: $font-size-base;
        color: $medium-gray;
        font-weight: $font-weight-medium;
        font-family: $font-family;
      }

      &.active {
        background: $blue-gradient;
        box-shadow: $shadow-blue;

        .sort-text {
          color: $white;
        }
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: $spacing-md;

    .action-btn {
      @include center-flex;
      gap: $spacing-sm;
      padding: $spacing-sm $spacing-lg;
      border-radius: $border-radius-3xl;
      background-color: $light-gray;
      cursor: pointer;
      transition: $transition-all;

      .action-text {
        font-size: $font-size-base;
        color: $medium-gray;
        font-weight: $font-weight-medium;
        font-family: $font-family;

        &.favorited {
          color: $coral;
        }
      }

      &.active {
        background-color: rgba(255, 149, 149, 0.1);
      }

      &:active {
        transform: scale(0.95);
      }
    }
  }
}

/* 绘本图片集列表 - 儿童友好风格 */
.picture-books-section {
  @include glass-effect;
  padding: $spacing-xl;
  margin: 0 $spacing-md;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;

  .section-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-semibold;
    color: $dark-gray;
    font-family: $font-family;
    margin-bottom: $spacing-xl;
  }

  .books-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: left;
    gap: $spacing-md;

    .book-grid-item {
      width: 30%; // 每行显示3个
      display: flex;
      flex-direction: column;
      cursor: pointer;
      transition: $transition-all;

      &:active {
        transform: scale(0.95);
      }

      .book-cover-container {
        position: relative;
        width: 100%;
        margin-bottom: $spacing-sm;

        .book-cover-grid {
          width: 100%;
          height: $book-cover-height; // 使用统一的绘本封面高度
          border-radius: $book-cover-radius;
          background-color: $light-gray;
          box-shadow: $shadow-lg;
        }

        // 阅读状态徽章
        .read-badge {
          position: absolute;
          top: $spacing-sm;
          left: $spacing-sm;
          padding: $spacing-xs $spacing-sm;
          background: $green-gradient;
          border-radius: $border-radius-md;
          font-size: $font-size-xs;
          color: $white;
          font-weight: $font-weight-medium;
          font-family: $font-family;
          box-shadow: $shadow-green;
        }

        // 未读状态徽章
        .unread-badge {
          position: absolute;
          top: $spacing-sm;
          left: $spacing-sm;
          padding: $spacing-xs $spacing-sm;
          background-color: $medium-gray;
          border-radius: $border-radius-md;
          font-size: $font-size-xs;
          color: $white;
          font-weight: $font-weight-medium;
          font-family: $font-family;
          box-shadow: $shadow-md;
        }

        // 绘本页数
        .book-pages {
          position: absolute;
          bottom: $spacing-sm;
          right: $spacing-sm;
          background-color: rgba(0, 0, 0, 0.5);
          color: $white;
          font-size: $font-size-sm;
          font-family: $font-family;
          padding: $spacing-xs $spacing-sm;
          border-radius: $border-radius-sm;
        }
      }

      .book-title-grid {
        font-size: $font-size-base;
        color: $dark-gray;
        font-weight: $font-weight-medium;
        font-family: $font-family;
        text-align: center;
        line-height: $line-height-tight;
        // 最多显示两行
        @include text-ellipsis-multiline(2);
        height: 36px; // 预留两行的高度
      }
    }
  }
}
</style>
